import Taro from '@tarojs/taro'
import { View, ScrollView } from '@tarojs/components'
import { useState, useCallback, useEffect } from 'react'
import './index.scss'

/**
 * 翻页组件
 * @param {Object} props - 组件属性
 * @param {Object} [props.containerStyle] - 容器样式
 * @param {Function} props.fetchData - 请求函数 (pageNum, pageSize) => Promise<{list: any[], total: number}>
 * @param {number} [props.pageSize=10] - 每页大小
 * @param {Function} props.renderItem - 渲染单个列表项的函数 (item, index) => ReactNode
 * @param {Function} [props.keyExtractor] - 生成列表项key的函数 (item, index) => string
 * @param {ReactNode} [props.emptyComponent] - 空列表提示组件
 * @param {boolean} [props.immediate=true] - 是否立即加载数据
 * @param {number} [props.lowerThreshold=50] - 滚动到底部触发加载的距离
 */
function PaginationComponent(props) {
    const {
        containerStyle = {},
        fetchData,
        pageSize = 10,
        renderItem,
        keyExtractor = (_, index) => index.toString(),
        emptyComponent = <View className="empty-text">暂无数据</View>,
        immediate = true,
        lowerThreshold = 50,
        params = []
    } = props
    console.log(params)
    const [state, setState] = useState({
        loading: false,
        list: [],
        pageNum: 1,
        total: 0,
        hasMore: true,
        refreshing: false,
    })
    useEffect(() => {

        setState({
            loading: false,
            list: [],
            pageNum: 1,
            total: 0,
            hasMore: true,
            refreshing: true,
        })
    }, [...params])
    // 加载数据
    const loadData = useCallback(async (isRefresh = false) => {
        if (state.loading) return

        const currentPage = isRefresh ? 1 : state.pageNum
        if (!isRefresh && !state.hasMore) return

        try {
            setState(prev => ({ ...prev, loading: true }))
            console.log(fetchData(currentPage, pageSize), 'fetch')
            const { list: newList, total: newTotal } = await fetchData(currentPage, pageSize)

            setState(prev => ({
                ...prev,
                list: isRefresh ? newList : [...prev.list, ...newList],
                total: newTotal,
                hasMore: newList.length >= pageSize,
                pageNum: isRefresh ? 2 : prev.pageNum + 1,
                loading: false,
                refreshing: false
            }))
        } catch (error) {
            console.error('加载数据失败:', error)
            setState(prev => ({ ...prev, loading: false, refreshing: false }))
        }
    }, [state.pageNum, state.hasMore, state.reloadFlag, state.loading, fetchData, pageSize])

    // 初始化加载
    useEffect(() => {
        if (immediate) {
            loadData(true)
        }
    }, [])

    // 下拉刷新
    const onRefresh = () => {
        setState(prev => ({ ...prev, refreshing: true }))
        loadData(true)
    }

    // 上拉加载更多
    const onScrollToLower = () => {
        if (!state.loading && state.hasMore) {
            loadData()
        }
    }

    return (
        <ScrollView
            style={containerStyle}
            scrollY
            refresherEnabled
            refresherTriggered={state.refreshing}
            onRefresherRefresh={onRefresh}
            lowerThreshold={lowerThreshold}
            onScrollToLower={onScrollToLower}
        >
            {/* 列表内容 */}
            {state.list.length > 0 ? (
                state.list.map((item, index) => (
                    <View key={keyExtractor(item, index)}>
                        {renderItem(item, index)}
                    </View>
                ))
            ) : (
                !state.loading && emptyComponent
            )}

            {/* 加载状态提示 */}
            {state.loading && (
                <View className="loading-text">
                    {state.list.length > 0 ? '加载中...' : '数据加载中...'}
                </View>
            )}

            {/* 没有更多提示 */}
            {!state.loading && state.list.length > 0 && !state.hasMore && (
                <View className="no-more-text">没有更多数据了</View>
            )}
        </ScrollView>
    )
}

export default PaginationComponent